package com.zoe.onelink.common.enumeration;

import com.fasterxml.jackson.annotation.JsonValue;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-07-15
 */
public interface BaseEnum<T extends Serializable> {


    /**
     * 枚举编码
     *
     * @return 编码
     */
    @JsonValue
    T getCode();

    /**
     * 枚举描述
     *
     * @return 描述
     */
    String getDesc();


    /**
     * 通过枚举类型和code值获取对应的枚举类型
     *
     * @param enumType 枚举类型
     * @param code     枚举编码
     * @return 枚举
     */
    static <T extends BaseEnum<Serializable>> T getByCode(Class<? extends BaseEnum<Serializable>> enumType, Serializable code) {
        if (enumType == null || code == null) {
            return null;
        }
        T[] enumConstants = (T[]) enumType.getEnumConstants();
        if (enumConstants == null) {
            return null;
        }
        for (T enumConstant : enumConstants) {
            Serializable enumCode = enumConstant.getCode();
            if (code.equals(enumCode)) {
                return enumConstant;
            }
        }
        return null;
    }

    /**
     * 将enum转换为list
     */
    static <T extends BaseEnum<Serializable>> List<Map<String, Object>> toListMap(Class<? extends BaseEnum<Serializable>> enumType) {
        if (enumType == null) {
            return null;
        }
        T[] enumConstants = (T[]) enumType.getEnumConstants();
        if (enumConstants == null) {
            return null;
        }
        ArrayList<Map<String, Object>> results = new ArrayList<>();
        for (T bean : enumConstants) {
            String desc = bean.getDesc();
            Serializable code = bean.getCode();
            HashMap<String, Object> map = new HashMap<>();
            map.put("code", code);
            map.put("desc", desc);
            results.add(map);
        }
        return results;
    }

}
